/*
 *
 *  * Copyright (c) GoKeep by gokeep.org. 2022-2023. All rights reserved
 *
 */

package org.gokeep.common.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;

import java.lang.reflect.Type;
import java.util.List;

/**
 * @author xuning
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class JsonUtil {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @SneakyThrows
    public static  <T> String toJson(T value) {
        return OBJECT_MAPPER.writeValueAsString(value);
    }

    @SneakyThrows
    public static  <T> String toJsonPrettify(T value) {
        return OBJECT_MAPPER.enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(value);
    }

    @SneakyThrows
    public static <T> byte[] toJsonBytes(T value) {
        return OBJECT_MAPPER.writeValueAsBytes(value);
    }

    @SneakyThrows
    public static <T> T toBean(String json) {
        return OBJECT_MAPPER.readValue(json, new TypeReference<>() {
            @Override
            public Type getType() {
                return super.getType();
            }
        });
    }

    @SneakyThrows
    public static <T> T toBean(String json, Class<T> classes) {
        return OBJECT_MAPPER.readValue(json, classes);
    }

    @SneakyThrows
    public static <T> T toBean(byte[] bytes, Class<T> classes) {
        return OBJECT_MAPPER.readValue(bytes, classes);
    }


    @SneakyThrows
    public static <T> T toBean(byte[] bytes) {
        return OBJECT_MAPPER.readValue(bytes, new TypeReference<>() {
            @Override
            public Type getType() {
                return super.getType();
            }
        });
    }


    @SneakyThrows
    public <T> List<T> toBeans(String json) {
        return OBJECT_MAPPER.readValue(json, new TypeReference<>() {
            @Override
            public Type getType() {
                return super.getType();
            }
        });
    }


}
